package com.wanghua.spring.test.xml;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;

/**
 * DOM解析。
 *
 * Element、Text类型节点对象都继承自 Node。
 */
public class DomDemo {
    public static void main(String[] args) {
        String userDir = System.getProperty("user.dir"); //D:\技术区\Java\Spring\Spring
        File xmlFile = new File(userDir + "/src/com/wanghua/spring/test/xml/article.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);    //获取文档对象模型
            Element root = document.getDocumentElement();  //获取根元素

            //1.xpath使用
            //select 可能返回 Element 对象，也可能是 Text 对象。如果 xpath 是 ".../text()"，则返回 Text 对象。
            XPath xpath = XPathFactory.newInstance().newXPath(); //用于xpath查询
            String titleString = (String) xpath.evaluate("/articles/article[@category='java']/title/text()", document,XPathConstants.STRING); //获取节点值
            Node titleNodes = (Node) xpath.evaluate("/articles/article[@category='java']/title", document,XPathConstants.NODE); //获取节点对象
            String category = (String) xpath.evaluate("/articles/article/@category", document,XPathConstants.STRING); //获取节点属性值（第一个 article 节点的）
            NodeList articles = (NodeList) xpath.evaluate("/articles/article", document, XPathConstants.NODESET); //获取节点集
            for (int i = 0; i < articles.getLength(); i++) {
                Node article = articles.item(i);
                category = (String) xpath.evaluate("@category", article, XPathConstants.STRING);
            }

            //2.遍历方式
            System.out.println("根元素：" + root.getNodeName());
            NodeList childNodes = root.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if ("article".equals(node.getNodeName())) {
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    Node namedItem = namedNodeMap.getNamedItem("category");
                    System.out.println("\r\n找到一篇文章，所属分类：" + namedItem.getNodeValue());

                    NodeList nodeDetail = node.getChildNodes(); //获得<article>下的节点
                    for (int j = 0; j < nodeDetail.getLength(); j++) {
                        Node detail = nodeDetail.item(j);
                        if ("title".equals(detail.getNodeName()))
                            System.out.println("标题：" + detail.getTextContent());
                        else if ("author".equals(detail.getNodeName()))
                            System.out.println("作者：" + detail.getTextContent());
                        else if ("email".equals(detail.getNodeName()))
                            System.out.println("电子邮件：" + detail.getTextContent());
                        else if ("date".equals(detail.getNodeName()))
                            System.out.println("发表日期：" + detail.getTextContent());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
